package com.example.demo;

import com.alibaba.fastjson.JSON;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: wuhong-016
 * @time: 2021/4/14 19:40
 * @version: v1.0.0
 * @description:TODO
 */
public class BuildRouteRequestJson {
    public static void main(String[] args) throws URISyntaxException {
        RouteDefinition definition = new RouteDefinition();
        PredicateDefinition predicate = new PredicateDefinition();
        Map<String, String> predicateParams = new HashMap<>(8);


// 生成json报文
//        routes:
//            - id: api-route  #路由的ID，没有固定规则但要求唯一，简易配合服务名
//            uri: lb://api         #匹配后提供服务的路由地址
//            predicates:
//                - Path=/test/**          #断言，路径相匹配的进行路由

        definition.setId("api-route");
        URI uri = new URI("lb://API-B");
        definition.setUri(uri);
        predicate.setName("Path");
        //请替换成本地可访问的路径
        predicateParams.put("pattern", "/test/**");
        predicate.setArgs(predicateParams);
        definition.setPredicates(Arrays.asList(predicate));

        System.out.println(JSON.toJSONString(definition));
    }

}
